package com.burgeon.backend.SHOP.service.Impl;

import com.burgeon.backend.SHOP.entity.*;
import com.burgeon.backend.SHOP.mappers.BargainMapper;
import com.burgeon.backend.SHOP.mappers.GoodsMapper;
import com.burgeon.backend.SHOP.mappers.OrderMapper;
import com.burgeon.backend.SHOP.rest.FindStoreData;
import com.burgeon.backend.SHOP.rest.Submit;
import com.burgeon.backend.SHOP.service.BargainService;
import com.burgeon.backend.SHOP.service.OrderService;
import com.burgeon.backend.SHOP.service.ex.OrderExceptionApp;
import com.burgeon.backend.SHOP.service.util.AddressUtil;
import com.burgeon.backend.SHOP.service.util.MathUtil;
import com.burgeon.backend.SHOP.service.util.ReducePriceUtils;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.service.QueueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

@Service
public class BargainServiceImpl implements BargainService {

    @Autowired
    private BargainMapper bargainMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private QueueService queueService;

    @Override
    public HashMap getMailFee(String barid) {
        BargainOrder bargainOrder = bargainMapper.findBargainOrderById(barid);
        BargainBean data = bargainMapper.findBargainBeanByID(bargainOrder.getBid());
        HashMap hashMap = new HashMap();
        hashMap.put("mailFee",data.getMailFee());
        return hashMap;
    }

    @Override
    public BargainOrder bargainOrderData(String barid) {
        BargainOrder bargainOrder = bargainMapper.findBargainOrderById(barid);
        bargainOrder.setGoods(bargainMapper.showGoodsById(bargainOrder.getGid()));
        return bargainOrder;
    }

    @Override
    public HashMap showStore(String longitude, String latitude, String token) {

        BigDecimal lon = new BigDecimal(longitude);
        BigDecimal lat = new BigDecimal(latitude);
        HashMap data = new HashMap();
        //获取店仓
        Info info = accountMapper.GetTokenData(token);
        FindStoreData findStoreData = new FindStoreData(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            List<Store> stores = findStoreData.getData();

            for (Store store : stores) {
                BigDecimal lons = new BigDecimal(store.getLongitude());
                BigDecimal lats = new BigDecimal(store.getLatitude());
                //计算距离
                double distance = AddressUtil.getDistance(lat.doubleValue(), lon.doubleValue(), lats.doubleValue(), lons.doubleValue());
                store.setDistance((double) Math.round(distance * 100) / 100);//保留一位小数 四舍五入
            }
            //排序

            Collections.sort(stores, new SortByAge());

            data.put("stores", stores);
            data.put("count", stores.size());
        } catch (Exception e) {
            e.printStackTrace();
            data.put("stores", new ArrayList<>());
            data.put("count", 0);
        }

        return data;
    }



    /**
     * 领取砍价商品
     *
     * @param barid
     * @param type  取货方式 KD  ZT
     * @param aid
     * @param store
     * @param phone
     * @param date  取件时间
     * @return
     * @throws OrderExceptionApp
     */
    @Override
    public PayData submitBargain(
            String barid, String type, String aid, String store,String distance, String phone, String date,
            String uid, String openid, String phoneZT, String nameZT, String token,String comment)
            throws OrderExceptionApp {
        BargainOrder bargainOrder = bargainMapper.findBargainOrderById(barid);
        BargainBean bargainBean = bargainMapper.findBargainBeanByID(bargainOrder.getBid());
        //判断 快递 自提
        PayData payData = new PayData();

        if ("ZT".equals(type)) {
            //自提支付
            payData = orderService.bargainCreateOrderZT(
                    uid, openid, phoneZT, nameZT, bargainOrder.getGid(), bargainOrder.getCode(),
                    store,distance, date, bargainOrder.getType(), phone, token,null,comment);
            //更改砍价单状态
            Integer row = bargainMapper.upBargainData(barid, "3", store, payData.getOrderId(), payData.getSelf(), type);

            if (1 != row) {
                throw new OrderExceptionApp("出现错误,稍后重试");
            }

        } else {
            //快递支付
            payData = orderService.bargainCreateOrder(uid, openid, aid, bargainOrder.getGid(), bargainOrder.getCode(),
                    bargainBean.getMailFee(), bargainOrder.getType(), phone, token,comment);
            //快递订单支付成功后接受回调后改状态
            Integer row = bargainMapper.upBargainData(barid, "2", store, payData.getOrderId(), payData.getSelf(), type);
        }

        return payData;
    }

    @Override
    @Transactional
    public HashMap hewBargain(String brid, String uid, String token) throws OrderExceptionApp {
        //获取砍价单数据
        BargainOrder bargainOrder = bargainMapper.findBargainOrderById(brid);

        BargainItem bargainItemdata = bargainMapper.findBargainItemByUidBarid(bargainOrder.getId(), uid);
        if (null!=bargainItemdata){
            throw new OrderExceptionApp("已砍价,可查看更多活动");
        }

        //获取砍价金额
        ArrayList<String> list = new ArrayList<String>(
                Arrays.asList(bargainOrder.getBargainBean()
                        .replace("[", "")
                        .replace("]", "")
                        .trim()
                        .split(",")));
        //减去剩余价格 修改数据库
        BigDecimal knife = null;
        try {
            knife = new BigDecimal(list.get(bargainOrder.getNowNeed()).trim());
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw new OrderExceptionApp("砍价已完成");
        }

        bargainMapper.upBalance(brid, knife);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(new Date());
        //创建砍价明细
        BargainItem bargainItem = new BargainItem();
        bargainItem.setUid(uid);
        bargainItem.setBarid(brid);
        bargainItem.setPrice(knife);
        bargainItem.setCreateTime(now);

        bargainMapper.createBargainItem(bargainItem);

        HashMap data = new HashMap();
        data.put("knife", knife);
        BargainVO bargainVO = bargainMapper.findBargainItemVO(brid);
        data.put("VO", bargainVO);
        data.put("state", "N");

        if (bargainOrder.getNeed() == bargainOrder.getNowNeed() + 1) {
            Order order = orderMapper.FindOrderERPData(bargainOrder.getOid());
            //完成砍价
            Info info = accountMapper.GetTokenData(token);
            Submit submit = new Submit(info.getUrl(), info.getAccount(), info.getPassword());
//            try {
//                submit.getData(order.getRetailCode(), "YC_RETAIL");//提交零售单
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            //更改订单状态
           // orderMapper.upOrderStateByID(bargainOrder.getOid(), "1", now);
            //更改砍价单状态
            bargainMapper.upBargainState(brid, "2");
            data.put("state", "Y");

            //a发送模板提醒
            //a.1根据uid获取oppenid
            Goods goods = goodsMapper.getGoods(bargainOrder.getGid());
            String openid = bargainMapper.findUserByUid(bargainOrder.getUid());
            System.err.println(bargainOrder.getUid());
//            System.err.println(bargainTemplate);
//            System.err.println(goods);
            //a,2发送
//            shopMessageTemplateService.sendBargain(openid,token,now,goods.getName());
            queueService.putBargain(openid,token,now,goods.getName());
        }
        return data;
    }

    @Override
    public BargainVO getBargainItem(String brid, String token) {

        BargainVO bargainItemVO = bargainMapper.findBargainItemVO(brid);
        System.err.println(bargainItemVO);
        if ("2".equals(bargainItemVO.getState())) {
            //砍价完成
            bargainItemVO.setState("Y");
        } else if ("3".equals(bargainItemVO.getState())) {
            //状态值为3 订单商品已领取 砍价完成
            bargainItemVO.setState("S");
        } else {
            bargainItemVO.setState("N");
        }

        if (null != bargainMapper.findBargainItemByID(brid) && !"3".equals(bargainItemVO.getState())) {
            bargainItemVO.setBargainItems(bargainMapper.findBargainItemByID(brid));
        }

        return bargainItemVO;
    }

    /**
     * 生成砍价单
     *
     * @param barid
     * @param uid
     * @param phone
     * @param openid
     * @param code
     * @param type
     * @param token
     * @return
     * @throws OrderExceptionApp
     */
    @Override
    public HashMap createBargain(String barid, String uid, String phone,
                                 String openid, String code, String type, String token)
            throws OrderExceptionApp {
        BargainBean bargainBean = bargainMapper.findBargainBeanByID(barid);
        Goods goods = bargainMapper.showGoodsById(bargainBean.getGid());
        //创建砍价单
        System.err.println(uid + "," + openid + "," +
                bargainBean.getGid() + "," + code + "," + type + "," + phone + "," + token);
        //    PayData data = orderService.bargainCreateOrder(uid, openid, aid, bargainBean.getGid(), code, type, phone, token);
        //创建云仓订单

        BargainOrder bargainOrder = new BargainOrder();
        bargainOrder.setGid(bargainBean.getGid());
        bargainOrder.setCode(code);
        bargainOrder.setType(type);
        bargainOrder.setToken(token);
        bargainOrder.setTotalPrice(new BigDecimal(goods.getPrice()));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(new Date());
        bargainOrder.setBalance(mathResidue(new BigDecimal(goods.getPrice())));
        List<Double> doubles = ReducePriceUtils.splitReducePrice(MathUtil.multiply(bargainOrder.getBalance(),
                BigDecimal.valueOf(100)).intValue(), bargainBean.getNeed());//分配砍价剩余金额
        bargainOrder.setBargainBean(doubles.toString());
        bargainOrder.setCreateTime(now);
        bargainOrder.setNeed(bargainBean.getNeed());
        bargainOrder.setNowNeed(0);
        bargainOrder.setState("1");//不需要支付操作 状态直接进行中
        bargainOrder.setEndTime(bargainBean.getEndTime());
        bargainOrder.setBid(bargainBean.getId());
        bargainOrder.setUid(uid);
            //bargainOrder.setOid(data.getOrderId());
        bargainOrder.setGid(bargainBean.getGid());
        bargainOrder.setType(type);
        bargainOrder.setCode(code);
        bargainMapper.createBargain(bargainOrder);
        HashMap hashMap = new HashMap();
        // hashMap.put("oid", data.getOrderId());
        hashMap.put("brid", bargainOrder.getId());
        return hashMap;
    }

    @Override
    public List<BargainBean> showBargainList(String uid, String token) {
        CopyOnWriteArrayList<BargainBean> bargainList = bargainMapper.getBargainList(token);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd" + " " + "HH:mm:ss");

        for (BargainBean bargainBean : bargainList) {
            bargainBean.setGoods(bargainMapper.showGoodsById(bargainBean.getGid()));
            //判断过期
            boolean judgeExpired = judgeExpired(sdf, bargainBean);
            System.err.println(judgeExpired);
            //判断是否已经拼团 brid uid

            if (!"null".equals(uid)) {

                if (null != bargainMapper.findBargainOrderByUidBarid(bargainBean.getId(), uid)) {
                    BargainOrder bargainOrder = bargainMapper.findBargainOrderByUidBarid(bargainBean.getId(), uid);
                    if ("1".equals(bargainOrder.getState())) {
                        bargainBean.setState("N"); //已发起砍价 去分享
                        if (!judgeExpired||"N".equals(bargainBean.getShow())){//已过期 隐藏
                            bargainList.remove(bargainBean);
                        }
                    } else if ("2".equals(bargainOrder.getState())) {
                        bargainBean.setState("S"); //砍价已完成 待领取
                    } else if ("3".equals(bargainOrder.getState())) {
                        bargainBean.setState("F"); //砍价已完成 已领取
                    }
                    bargainBean.setBarid(bargainMapper.findBargainOrderByUidBarid(bargainBean.getId(), uid).getId());
                } else {
                    bargainBean.setState("Y");//没发起砍价 去砍价
                    if (!judgeExpired||"N".equals(bargainBean.getShow())){
                        bargainList.remove(bargainBean);
                    }
                }

            } else {

                bargainBean.setState("Y");//没发起砍价 去砍价
                if (!judgeExpired||"N".equals(bargainBean.getShow())){
                    bargainList.remove(bargainBean);
                }
            }
        }
        //判断是否已经拼团 brid uid

        /*if (!"null".equals(uid)) {
            for (BargainBean bargainBean : bargainList) {
                if (null != bargainMapper.findBargainOrderByUidBarid(bargainBean.getId(), uid)) {
                    BargainOrder bargainOrder = bargainMapper.findBargainOrderByUidBarid(bargainBean.getId(), uid);
                    if ("1".equals(bargainOrder.getState())) {
                        bargainBean.setState("N"); //已发起砍价 去分享
                    } else if ("2".equals(bargainOrder.getState())) {
                        bargainBean.setState("S"); //砍价已完成 待领取
                    } else if ("3".equals(bargainOrder.getState())) {
                        bargainBean.setState("F"); //砍价已完成 已领取
                    }
                    bargainBean.setBarid(bargainMapper.findBargainOrderByUidBarid(bargainBean.getId(), uid).getId());
                } else {
                    bargainBean.setState("Y");//没发起砍价 去砍价
                }
            }

        } else {
            for (BargainBean bargainBean : bargainList) {
                bargainBean.setState("Y");//没发起砍价 去砍价
            }
        }*/
        return bargainList;
    }

    private boolean judgeExpired(SimpleDateFormat sdf, BargainBean bargainBean) {
        try {
            Date parse = sdf.parse(bargainBean.getEndTime());
            //过期更改状态
            if (parse.getTime() < new Date().getTime()) {
                bargainMapper.upBargainBeanState(bargainBean.getId(), "N");
                return false;
            }
            return true;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }


    private static BigDecimal mathResidue(BigDecimal tot) {
        return MathUtil.divide(MathUtil.multiply(tot,
                new BigDecimal(
                        new Random().nextInt(10) + 40))
                , new BigDecimal(100));
    }


    public static void main(String[] args) {
        //114.556688,38.049483
        //114.570603,38.050367
        double distance = AddressUtil.getDistance(
                38.043667, 114.54407, 38.050367, 114.570603);
        distance=(double) Math.round(distance * 100) / 100;
        System.err.println(distance);
    }

}

class SortByAge implements Comparator {
    public int compare(Object o1, Object o2) {
        Store s1 = (Store) o1;
        Store s2 = (Store) o2;

        if (s1.getDistance() > s2.getDistance())
            return 1;
        return -1;
        //不用写s1.getAge()==s2.getAge()的情况
    }

}
